package com.tuuzed.android.sample.activity

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import com.tuuzed.android.base.BaseActivity
import com.tuuzed.android.eventbus.EventBus
import com.tuuzed.android.eventbus.Subscribe
import com.tuuzed.android.sample.R
import com.tuuzed.android.utilkt.toastShort

class EventBusActivity : BaseActivity() {
    override fun isHomeAsUpEnabled(): Boolean = true
    override fun isSwipeBackEnable(): Boolean = true
    private lateinit var mBtnRegister: Button
    private lateinit var mBtnUnregister: Button
    private lateinit var mBtnPostEvent: Button
    private lateinit var mBtnPostStickyEvent: Button
    private lateinit var mBtnToStickyEventReceiver: Button


    override fun onCreate(bundle: Bundle?) {
        super.onCreate(bundle)
        setContentView(R.layout.eventbus_act)
        setSupportActionBar(findViewById(R.id.toolbar))
        mBtnRegister = findViewById(R.id.btn_register)
        mBtnUnregister = findViewById(R.id.btn_unregister)
        mBtnPostEvent = findViewById(R.id.btn_post_event)
        mBtnPostStickyEvent = findViewById(R.id.btn_post_sticky_event)
        mBtnToStickyEventReceiver = findViewById(R.id.btn_to_sticky_event_receiver)

        mBtnRegister.setOnClickListener { EventBus.getDefault().register(this) }
        mBtnUnregister.setOnClickListener { EventBus.getDefault().unregister(this) }
        mBtnPostEvent.setOnClickListener { EventBus.getDefault().post(Event("Event")) }
        mBtnPostStickyEvent.setOnClickListener { EventBus.getDefault().postSticky(StickyEvent("StickyEvent")) }
        mBtnToStickyEventReceiver.setOnClickListener {
            startActivity(Intent(this, EventBusActivity2::class.java))
        }
    }

    @Subscribe(threadMode = EventBus.MAIN)
    fun onEvent(event: Event) {
        toastShort(event.toString())
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    data class Event(val msg: String)
    data class StickyEvent(val msg: String)
}
